package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"project_file_manager/conn"
	//"project_file_manager/conn"
	"project_file_manager/model"
	"project_file_manager/service/storage"
)

const FileDir = "D:/root/"

func init() {
	//打开目录
	localFileInfo, fileStatErr := os.Stat(FileDir)
	//目录不存在
	if fileStatErr != nil || !localFileInfo.IsDir() {
		//创建目录
		errByMkdirAllDir := os.MkdirAll(FileDir, 0755)
		if errByMkdirAllDir != nil {
			panic("请手动创建文件夹再启动程序， 文件夹位置：" + FileDir)
		}
	}
}

// UploadFile 文件上传
func UploadFile(c *gin.Context) {
	name, path, err := storage.SaveUploadFile(c)
	if err != nil {
		fmt.Printf(err.Error())
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"message": err.Error(),
		})
		return
	}
	info := model.FileInfo{Name: name, Path: path}
	info.Save()
	fmt.Printf("param: %s\n", c.PostForm("comments"))
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		//"name":    file.Filename,
		//"path":    filename,
		"message": "上传成功",
	})
	//file, err := c.FormFile("file")
	//if err != nil {
	//	c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
	//	return
	//}
	////上传后的文件名，需要进行入库
	//filename := FileDir +filepath.Base(file.Filename)
	//if err := c.SaveUploadedFile(file, filename); err != nil {
	//	fmt.Printf(err.Error())
	//	c.JSON(http.StatusOK, gin.H{
	//		"success": false,
	//		"name":    "",
	//		"path":    filename,
	//		"message": err.Error(),
	//	})
	//	return
	//}
	//fmt.Printf("param: %s\n",c.PostForm("comments"))
	//c.JSON(http.StatusOK, gin.H{
	//	"success": true,
	//	"name":    file.Filename,
	//	"path":    filename,
	//	"message": "上传成功",
	//})
}

// DownloadFile 文件下载
func DownloadFile(c *gin.Context) {
	//fileId := c.Param("id")
	//
	//file:=storage.GetFile(path)
	//c.Writer.Header().Add("Content-Disposition",fmt.Sprintf("attachment;filename=%s",file.Filename))
	//c.File("./"+file.Filename)  //返回文件路径，自动调用http.ServeFile方法
}

// DeleteFile 文件删除
func DeleteFile(context *gin.Context) {

}

func NewFileModel(context *gin.Context) {

}

func DeleteFileModel(context *gin.Context) {

}

func GetFileModel(c *gin.Context) {
	id := c.Param("id")
	var res interface{}
	if id == "" || "/" == id {
		info := model.FileInfo{}
		res, _ = info.GetAll()

	} else {

		fileInfo := model.FileInfo{}
		conn.GetDB().First(&fileInfo, id)
		res = fileInfo
	}
	fmt.Println(res)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		//"name":    file.Filename,
		//"path":    filename,
		"message": "",
		"data":    res,
	})
}

func UpdateFileModel(context *gin.Context) {

}

// PageQRCode 显示二维码页面
func PageQRCode(context *gin.Context) {

}

// PageIndex 显示首页
func PageIndex(c *gin.Context) {
	c.HTML(200, "index.tmpl", gin.H{
		"title":  "首页",
		"title2": "文件列表",
	})
}
